/**
 * 副将仓库系统测试 - 1419和1420指令
 * 
 * 测试功能：
 * 1. 1419 - 查看副将列表（包括可以放到仓库的副将和仓库中的副将）
 * 2. 1420 - 副将仓库操作（存储到仓库和从仓库提取）
 */

const WebSocket = require('ws');

const CONFIG = {
    wsUrl: 'ws://localhost:3000/user-service/websocket',
    testUser: {
        username: 'testuser',
        password: 'testpass'
    },
    testCharacter: {
        name: '测试角色',
        headIndex: 1
    }
};

class DeputyWarehouseTester {
    constructor() {
        this.ws = null;
        this.token = null;
        this.characters = [];
        this.deputyList = [];
        this.warehouseList = [];
        this.testResults = [];
    }

    async connect() {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(CONFIG.wsUrl);

            this.ws.on('open', () => {
                console.log('🔗 WebSocket连接已建立');
                resolve();
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    this.handleWebSocketResponse(message);
                } catch (error) {
                    console.error('解析消息失败:', error);
                }
            });

            this.ws.on('error', (error) => {
                console.error('WebSocket错误:', error);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
            });
        });
    }

    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
            console.log('📤 发送消息:', JSON.stringify(message, null, 2));
        } else {
            console.error('WebSocket未连接');
        }
    }

    handleWebSocketResponse(message) {
        const { act_id, code, msg, data, list, sum, type } = message;

        switch (act_id) {
            case 1: // 登录
                if (code === 0) {
                    this.token = data.token;
                    console.log('✅ 登录成功，token:', this.token);
                } else {
                    console.error('❌ 登录失败:', msg);
                }
                break;

            case 3: // 角色列表
                if (list && Array.isArray(list)) {
                    this.characters = list;
                    console.log(`📋 获取到${list.length}个角色`);
                }
                break;

            case 4: // 角色选择
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                } else {
                    console.error('❌ 角色选择失败:', msg);
                }
                break;

            case 1419: // 副将仓库列表
                this.testResults.push({
                    act_id: 1419,
                    code: code,
                    msg: msg,
                    list: list || [],
                    sum: sum || 0,
                    type: type || 0,
                    timestamp: new Date().toISOString()
                });

                if (code === 0) {
                    console.log(`📦 副将仓库列表获取成功: 类型${type}, 数量${sum}`);
                    console.log('📊 副将详情:', JSON.stringify(list, null, 2));

                    if (type === 0) {
                        this.deputyList = list;
                    } else if (type === 2) {
                        this.warehouseList = list;
                    }
                } else {
                    console.error('❌ 副将仓库列表获取失败:', msg);
                }
                break;

            case 1420: // 副将仓库操作
                this.testResults.push({
                    act_id: 1420,
                    code: code,
                    msg: msg,
                    timestamp: new Date().toISOString()
                });

                if (code === 0) {
                    console.log(`✅ 副将仓库操作成功: ${msg}`);
                } else {
                    console.error('❌ 副将仓库操作失败:', msg);
                }
                break;

            default:
                console.log(`📨 收到消息: act_id=${act_id}, code=${code}, msg=${msg}`);
        }
    }

    async login() {
        console.log('\n🔐 步骤1: 用户登录...');
        this.sendMessage({
            c: 1,
            d: CONFIG.testUser
        });

        // 等待登录响应
        await this.waitForResponse(1);
    }

    async queryCharacters() {
        console.log('\n📋 步骤2: 查询角色列表...');
        this.sendMessage({
            c: 3,
            d: {}
        });

        // 等待角色列表响应
        await this.waitForResponse(3);
    }

    async selectCharacter() {
        if (this.characters.length === 0) {
            console.log('❌ 没有可用角色，创建新角色...');
            await this.createCharacter();
        }

        console.log('\n🎯 步骤3: 选择角色...');
        const character = this.characters[0];
        this.sendMessage({
            c: 4,
            d: {
                id: character.id
            }
        });

        // 等待角色选择响应
        await this.waitForResponse(4);
    }

    async createCharacter() {
        console.log('\n🆕 创建新角色...');
        this.sendMessage({
            c: 5,
            d: {
                name: CONFIG.testCharacter.name,
                headIndex: CONFIG.testCharacter.headIndex
            }
        });

        // 等待角色创建响应
        await this.waitForResponse(5);
    }

    async testDeputyWarehouseList() {
        console.log('\n📦 步骤4: 测试副将仓库列表功能...');

        // 测试1: 查看可以放到仓库的副将列表
        console.log('\n📋 测试1: 查看可以放到仓库的副将列表 (action=0)');
        this.sendMessage({
            c: 1419,
            d: {
                action: 0,
                pageNum: 0,
                sort: 0
            }
        });
        await this.waitForResponse(1419);

        // 测试2: 查看仓库中的副将列表
        console.log('\n📋 测试2: 查看仓库中的副将列表 (action=2)');
        this.sendMessage({
            c: 1419,
            d: {
                action: 2,
                pageNum: 0,
                sort: 0
            }
        });
        await this.waitForResponse(1419);

        // 测试3: 按分类查看副将列表
        console.log('\n📋 测试3: 按分类查看副将列表 (sort=1)');
        this.sendMessage({
            c: 1419,
            d: {
                action: 0,
                pageNum: 0,
                sort: 1
            }
        });
        await this.waitForResponse(1419);
    }

    async testDeputyWarehouseOperation() {
        console.log('\n⚙️ 步骤5: 测试副将仓库操作功能...');

        // 如果有可以存储的副将，测试存储操作
        if (this.deputyList.length > 0) {
            const deputyToStore = this.deputyList[0];
            console.log(`\n📦 测试1: 存储副将到仓库 (id=${deputyToStore.id})`);
            this.sendMessage({
                c: 1420,
                d: {
                    id: deputyToStore.id,
                    action: 1,
                    pageNum: 0
                }
            });
            await this.waitForResponse(1420);
        } else {
            console.log('⚠️ 没有可存储的副将，跳过存储测试');
        }

        // 如果有仓库中的副将，测试提取操作
        if (this.warehouseList.length > 0) {
            const deputyToRetrieve = this.warehouseList[0];
            console.log(`\n📦 测试2: 从仓库提取副将 (id=${deputyToRetrieve.id})`);
            this.sendMessage({
                c: 1420,
                d: {
                    id: deputyToRetrieve.id,
                    action: 2,
                    pageNum: 0
                }
            });
            await this.waitForResponse(1420);
        } else {
            console.log('⚠️ 没有可提取的副将，跳过提取测试');
        }
    }

    async waitForResponse(expectedActId, timeout = 5000) {
        return new Promise((resolve) => {
            const startTime = Date.now();
            const checkResponse = () => {
                const response = this.testResults.find(r => r.act_id === expectedActId);
                if (response) {
                    resolve(response);
                } else if (Date.now() - startTime > timeout) {
                    console.log(`⏰ 等待响应超时 (act_id=${expectedActId})`);
                    resolve(null);
                } else {
                    setTimeout(checkResponse, 100);
                }
            };
            checkResponse();
        });
    }

    async runTests() {
        try {
            console.log('🚀 开始副将仓库系统测试...');

            await this.connect();
            await this.login();
            await this.queryCharacters();
            await this.selectCharacter();
            await this.testDeputyWarehouseList();
            await this.testDeputyWarehouseOperation();

            console.log('\n📊 测试结果汇总:');
            console.log(JSON.stringify(this.testResults, null, 2));

            console.log('\n✅ 副将仓库系统测试完成！');

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error);
        } finally {
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
const tester = new DeputyWarehouseTester();
tester.runTests().catch(console.error);
